﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using log4net;
using Common;
using CashFlow.Db.Entity;
using SysAdmin._01_Config;
using SysAdmin._02_Common;
using SysAdmin._03_Service;
using SysAdmin._03_Service._00_Db;
using SysAdmin._04_Form._00_Common;

namespace SysAdmin._04_Form._03_Order
{
    public partial class AddOrderForm : Form
    {
        private static ILog _logger = LogManager.GetLogger(typeof(AddOrderForm));
        private Timer _timer = new Timer();
        private IList<UserInfoEntity> _users;
        private int _buyerUserId = 0;
        private int _sellerUserId = 0;

        public AddOrderForm()
        {
            InitializeComponent();
        }

        private void AddOrderForm_Load(object sender, EventArgs e)
        {
            _timer.Interval = 100;
            _timer.Tick += _timer_Tick;
        }

        private void AddOrderForm_Shown(object sender, EventArgs e)
        {
            _timer.Start();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            try
            {
                _timer.Stop();
                _users = UserService.QueryAllUsers2();
                var ls = _users.Select(x => string.Format("{0}-{1}", x.Name, x.Phone)).ToList();
                FillListView(listView1, ls);
                FillListView(listView2, ls);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var info = listView1.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                label3.Text = info.Item.Text;
                string[] arr = info.Item.Text.Split('-');
                if (arr != null && arr.Length == 2)
                {
                    var item = _users.Where(x => x.Phone == arr[1].Trim()).FirstOrDefault();
                    if (item != null)
                    {
                        _buyerUserId = item.Id;
                    }
                }
            }
        }

        private void listView2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var info = listView2.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                label4.Text = info.Item.Text;
                string[] arr = info.Item.Text.Split('-');
                if (arr != null && arr.Length == 2)
                {
                    var item = _users.Where(x => x.Phone == arr[1].Trim()).FirstOrDefault();
                    if (item != null)
                    {
                        _sellerUserId = item.Id;
                    }
                }
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            var ls = _users.Where(x => x.Name.Contains(textBox2.Text.Trim()))
                        .Select(x => string.Format("{0}-{1}", x.Name, x.Phone))
                        .ToList();
            FillListView(listView1, ls);
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            var ls = _users.Where(x => x.Name.Contains(textBox3.Text.Trim()))
                        .Select(x => string.Format("{0}-{1}", x.Name, x.Phone))
                        .ToList();
            FillListView(listView2, ls);
        }

        private void FillListView(ListView lv, IList<string> ls)
        {
            lv.BeginUpdate();
            lv.Items.Clear();
            foreach (var item in ls)
            {
                lv.Items.Add(item);
            }
            lv.EndUpdate();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateForm())
                {
                    string date = TimeService.Now.ToString("yyyy-MM-dd");
                    if (OrderService.IsExistOrder(_buyerUserId, date))
                    {
                        string name = label3.Text.Split('-')[0];
                        string str = string.Format("买家({0})今日已有订单！", name);
                        UICommonTool.ShowAlertDialog(str);
                    }
                    else
                    {
                        var order = new OrderEntity();
                        order.Name = GetProductName();
                        order.BuyerUserId = _buyerUserId;
                        order.SellerUserId = _sellerUserId;
                        order.CreateTime = TimeService.Now;
                        order.OrderNo = ServiceCommonTool.CreateOrderNo();
                        order.State = 0;
                        order.PaymentVoucherImagePath = "";
                        order.Visible = 1;
                        decimal amount = Convert.ToDecimal(textBox1.Text.Trim());
                        decimal amount2 = Convert.ToDecimal(MyCommonTool.ToString(amount));
                        order.Amount = amount2;
                        bool b = OrderService.Add(order);
                        if (b)
                        {
                            UICommonTool.ShowInfoDialog("创建成功！");
                            _buyerUserId = _sellerUserId;
                            _sellerUserId = 0;
                            label3.Text = label4.Text;
                            label4.Text = "未选择！";
                            textBox1.Text = "";
                            textBox3.Focus();
                        }
                        else
                        {
                            UICommonTool.ShowAlertDialog("创建失败！");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private bool ValidateForm()
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                UICommonTool.ShowAlertDialog("请先输入金额！");
                return false;
            }
            decimal value = 0M;
            bool b = decimal.TryParse(textBox1.Text.Trim(), out value);
            if (!b)
            {
                UICommonTool.ShowAlertDialog("请输入正确格式的金额！");
                return false;
            }
            if (!(value >= 1000 && value <= 15000))
            {
                UICommonTool.ShowAlertDialog("金额必须在1000 - 15000之间！");
                return false;
            }
            if (_buyerUserId == 0)
            {
                UICommonTool.ShowAlertDialog("请选择买家！");
                return false;
            }
            if (_sellerUserId == 0)
            {
                UICommonTool.ShowAlertDialog("请选择卖家！");
                return false;
            }
            if (_buyerUserId == _sellerUserId)
            {
                UICommonTool.ShowAlertDialog("买家和卖家不能是同一家！");
                return false;
            }
            return true;
        }

        private string GetProductName()
        {
            int index = RandTool.CreateRandValWithMinMax(0, MyConfig.ProductNames.Count - 1);
            return MyConfig.ProductNames.ElementAt(index);
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                if (_buyerUserId > 0 && _sellerUserId > 0)
                {
                    button1_Click(button1, null);
                }
            }

            return base.ProcessDialogKey(keyData);
        }
    }
}
